class BTWrapper
  attr :log_file
  attr :dl_rate
  attr :ul_rate
  attr :save_as
  attr :percent_done
  attr :time_left
  attr :destination
  attr :pid

  def initialize(episode, url, dest)
    log_directory = Configuration.find(:first).bt_log_dir
    @log_file = log_directory + "/" + "#{episode.get_show.title.gsub(/ /, "-").gsub(/[&]/, 'and').gsub(/\!/, '')}_#{episode.season}_#{episode.episode}.log"
    puts "HERE IS THE LOG FILE @log_file"
    @destination = dest.gsub(/([&!:])/, '')
    @url = url
    @dl_rate = 0;
    @ul_rate = 0;
    @percent_done = 0
    @time_left = ""
  end

  def start_download()
    execute_bt_command = "btdownloadheadless #{@url} --saveas #{@destination}"
    catter_location = "#{File.dirname(__FILE__)}/catter.pl"
    puts "Destination: #{@destination}"
    
#    bt_thread = Thread.new do
     #@pid = exec("btdownloadheadless #{@url} --saveas #{@destination} | #{catter_location} #{@log_file} ") if fork.nil?
     @pid = fork { exec("btdownloadheadless #{@url} --saveas #{@destination} | #{catter_location} #{@log_file} ") }
     puts "PID is #{@pid}"

    thread = Thread.new do 
      while true
        update_info
        puts "Percent Done: #{@percent_done} Time Left: #{@time_left} Download Rate: #{@dl_rate} Upload Rate: #{@ul_rate}"
        if finished?
          done_callback
        end
        sleep 5
      end
    end
    #thread.join
  end

  def finished?
    @time_left == "Download Succeeded!" || "Download Failed!"
  end

  def done_callback
    puts "THIS ONE IS DONE!"
    puts "Killing #{@pid}"
    Process.kill("USR1", @pid)
    
  end

  def update_info
    f = File.open(@log_file)
    lines = f.readlines
    f.close
    #f.each_line do |line|
    lines.each do |line|
      #grep for specific thing in the line
      if line =~ /(percent done:)\s+/ 
      	@percent_done = $'.chomp
      end
      if line =~ /(time left:)\s+/ 
      	@time_left = $'.chomp
      end
      if line =~ /(download rate:)\s+/ 
      	@dl_rate = $'.chomp
      end
      if line =~ /(upload rate:)\s+/ 
      	@ul_rate = $'.chomp
      end
    end
  end
end
